define(['FormCheck'], function(){
    /*
    config选项
    candidateDataList 待选择列表
    disableIdList 禁用id列表
    callback 回调函数
        submit: 提交回调
        candidateDataUpdate: 候选更新
        searchChange: 网络请求搜索用户,不传则是本地搜索

    userTypeName 联系人类型 student teacher
    hasAddContact 添加联系人按钮
    searchIntervalTime: 默认是2000(单位毫秒)
    candidateLength: 待选择长度
    checkedDataList 选中列表 （可选）
    checkedMax 最大可选数量 （可选）

    实例属性
    popUpBox 弹出窗实例
    candidateList
    checkedList

    实例方法
    getCheckedIdList 获取选中id列表
    getCheckedDataList 获取选中数据列表
    */
	var ContactSelector=function (config){
        var selector = this
        // window.selector = selector
		var defaultAvatarImgSrc = 'img/avatar.png'
        config.userTypeName || (config.userTypeName = '用户')
        config.hasAddContact || (config.hasAddContact = false)
        config.disableListGroup=config.disableListGroup || {};
        config.candidateDataList || (config.candidateDataList = {})
        config.searchIntervalTime || (config.searchIntervalTime = 2000)
        config.hideAvatar === undefined && (config.hideAvatar = false)

        //Candidate
        function Candidate (contactData) {
            var contact = this
            contact.$dom = $('<li class="contact" data-contactid="'+ contactData.id +'"></li>');

            //禁用列表检查
            $.each(config.disableListGroup, function (key, curObj) {
                if(curObj.disableList.indexOf(contactData.id) > -1) {
                    contact.$dom.addClass('disabled')
                    contact.$dom.attr('title', curObj.disableInfo)
                }
            })

            contact.$avatarBox = $('<div class="icon icon-size-40 icon-avatar"></div>').appendTo(contact.$dom)
            contact.$avatarImg = $('<img>').appendTo(contact.$avatarBox)
            if(config.hideAvatar){
                contact.$dom.addClass('hideAvatar');
            }
            contact.$name = $('<div class="name"></div>').appendTo(contact.$dom)
            contact.$pinyin = $('<div class="pinyin"></div>').appendTo(contact.$dom)
            contact.$description = $('<div class="description"></div>').appendTo(contact.$dom)
            contact.$checkboxBtn = $('<div class="icon icon-size-16 icon-checkbox"></div>').appendTo(contact.$dom)

            contact.$dom.on('click', function () {
                if(contact.$dom.hasClass('disabled')) {
                    return
                }
                if(contact.$dom.hasClass('checked')){
                    selector.checkedList.remove(contactData.id)
                    contact.check(false)
                } else if(config.checkedMax == 1) {
                    selector.checkedList.update({id: contactData})
                    selector.candidateList.checkAll(false)
                    contact.check(true)
                } else if (config.checkedMax && config.checkedMax <= Object.keys(selector.checkedList.newList).length) {
                        _Tips('已达到最大人数限制');
                } else {
                    selector.checkedList.add(contactData)
                    contact.check(true)
                }
            })

	    	contact.show(contactData)
        }

        Candidate.prototype = {
            show: function (contactData) {
                var contact = this
                contact.$avatarImg.attr('src', contactData.avatar || defaultAvatarImgSrc)
                contact.$name.text(contactData.name)
                contact.$pinyin.text(contactData.name)
                contact.$description.text(contactData.phone)

                if(selector.checkedList.newList[contactData.id]) {
                    this.check(true)
                }
            },
            check: function (isCheck) {
                var contact = this
                if (isCheck) {
                    contact.$dom.addClass('checked')
                    contact.$checkboxBtn.addClass('checked')
                } else {
                    contact.$dom.removeClass('checked')
                    contact.$checkboxBtn.removeClass('checked')
                }
            }
        }

        //CandidateList
        function CandidateList(candidateDataList) {
            this.$dom = $('<ul class="contactList"></ul>')
            this.$selectAll = $('<li class="selectAll">全选</li>')
            this.$selectAllIcon = $('<div class="icon icon-size-16 icon-checkbox"></div>').appendTo(this.$selectAll)
            this.data = {}
            this.newList = {}

            if(typeof candidateDataList == 'object') {
                this.init(candidateDataList)
            }
        }

        CandidateList.prototype = {
            showTotalCount: function () {
                selector.$totalCount.text(Object.keys(this.newList).length)
            },
            init: function (dataList) {
                this.$dom.show()
                selector.$emptyContent.hide()
                if(!dataList || Object.keys(dataList).length < 1) {
                    this.$dom.hide()
                    selector.$emptyContent.show()
                    if(typeof config.callback.candidateDataUpdate == 'function') {
                        config.callback.candidateDataUpdate(selector.$emptyContent)
                    }
                    return
                }

                for (var key in dataList) {
                    if (dataList.hasOwnProperty(key)) {
                        var contactData = dataList[key]
                        if(contactData.avatar == '') {
                            contactData.avatar = defaultAvatarImgSrc
                        }
                        this.add(contactData)
                    }
                }
            },
            add: function (contactData) {
                if(!this.data[contactData.id]) {
                    this.data[contactData.id] = contactData
                    this.newList[contactData.id] = new Candidate(contactData)
                    this.$dom.append(this.newList[contactData.id].$dom)
                }
            },
            update: function (dataList) {
                this.newList = {}
                this.data = {}
                this.$dom.html('')
                this.init(dataList)
            },
            isIncludeByPhone: function (phone) {
                var cdList = this
                var flag = false;
                $.each(cdList.newList, function (key, value) {
                    if(value.data.phone === phone) {
                        flag = true
                        return false
                    }
                })
                return flag
            },
            checkAll: function (isCheck) {
                var cdList = this
                $.each(cdList.newList, function (key, value) {
                    value.check(isCheck)
                })
            }
        }

        //Checked
        function Checked (contactData) {
            var contact = this
            contact.$dom = $('<li class="contact" data-contactid="'+ contactData.id +'"></li>')
            contact.$avatarBox = $('<div class="icon icon-size-40 icon-avatar"></div>').appendTo(contact.$dom)
            contact.$avatarImg = $('<img>').appendTo(contact.$avatarBox)
            if(config.hideAvatar){
                contact.$dom.addClass('hideAvatar');
            }
            contact.$name = $('<div class="name"></div>').appendTo(contact.$dom)
            contact.$pinyin = $('<div class="pinyin"></div>').appendTo(contact.$dom)
            contact.$description = $('<div class="description"></div>').appendTo(contact.$dom)

            contact.$removeBtn = $('<div class="icon icon-size-16 icon-remove"></div>').appendTo(contact.$dom)
            contact.$removeBtn.on('click', function () {
                selector.checkedList.remove(contactData.id)
                contact.$dom.removeClass('checked')
            })

	        contact.show(contactData)
        }

        Checked.prototype = {
            show: function (contactData) {
                var contact = this
                contact.$avatarImg.attr('src', contactData.avatar || defaultAvatarImgSrc)
                contact.$name.text(contactData.name)
                contact.$pinyin.text(contactData.name)
                contact.$description.text(contactData.phone)
            }
        }

        //CheckedList
        function CheckedList(checkedDataList) {
            this.$dom = $('<ul class="contactList"></ul>')
            this.data = {}
            this.newList = {}

            if(typeof checkedDataList == 'object') {
                this.init(checkedDataList)
            }
        }

        CheckedList.prototype = {
            showCheckedNum: function () {
                selector.$selectCount.text(Object.keys(this.newList).length)
            },
            init: function (DataList) {
                for (var key in DataList) {
                    if (DataList.hasOwnProperty(key)) {
                        var contactData = DataList[key]
                        if(contactData.avatar == '') {
                            contactData.avatar = defaultAvatarImgSrc
                        }
                        this.add(contactData)
                    }
                }
            },
            add: function (contactData) {
                if(!this.data[contactData.id]) {
                    this.data[contactData.id] = contactData
                    this.newList[contactData.id] = new Checked(contactData)
                    this.$dom.append(this.newList[contactData.id].$dom)

                    this.showCheckedNum()
                }
            },
    	    update: function (dataList) {
                this.newList = {}
                this.data = {}
                this.$dom.html('')
                this.init(dataList)
            },
            remove: function (id) {
                if(Object.keys(this.newList).length) {
                    this.newList[id].$dom.remove()
                    delete this.data[id]
                    delete this.newList[id]
                    if(selector.candidateList.newList[id]) {
                        selector.candidateList.newList[id].check(false)
                    }
                    this.showCheckedNum()
                }
            },
            getCheckedDataList: function () {
                return this.data
            }
        }

        function SearchBar() {
            var searchBar = this
            searchBar.$dom = $('<div data-type="searchbar">'+
    								'<input type="text" class="form-control" data-type="search-input" data-searchlist=".addContactTools .candidateContactList .contact" value="账号 / 姓名" data-tips="账号 / 姓名" /><input type="button" class="form-control" data-type="search-button">'+
    							'</div>')
            var $searchInput = searchBar.$dom.find('[data-type="search-input"]')
            var $searchButton = searchBar.$dom.find('[data-type="search-button"]')

            if(typeof config.callback.searchChange == 'function') {

                //立即搜素
                function searchCallback() {
                    var query = $.trim($searchInput.value())
                    config.callback.searchChange(query)
                }

                /*//延迟搜索
                var searchCallbackDelay = (function () {
                    return $.debounce(searchCallback, 2000)
                })()*/

                var timer = null;

                $searchInput
                .on('keyup', function (e) {
                	e.stopPropagation()
                    if(e.ctrlKey || e.altKey || e.keyCode==17 || e.keyCode==18) {
                        return
                    }
                    clearTimeout(timer)
                    if(e.keyCode === 13) {
                        searchCallback()
                    } else {
                        timer = setTimeout(searchCallback, config.searchIntervalTime)
                    }
                })
                .on('focus', function () {
                    $searchButton.prop('disabled', false)
                })

                $searchButton.on('click', function () {
                    clearTimeout(timer)
                    searchCallback()
                    $(this).prop('disabled', true)
                })

            } else {
                $searchInput.attr('data-searchtag', '.name,.description,.pinyin')
            }

        }

        var popUpBox=new PopUpBox({
			type:'dom',
			style:'default autoResize',
			submitBtnType:'confirm',
			titleText:'请选择',
			drag:true,
			// content:selector.$dom,
			callback:{
				'yes':function(e){
					// config.callback.submit(Object.keys(selector.checkedList.newList))
					if( config.callback.submit(selector.getCheckedDataList()) == false ) {
                        return false
                    }
				}
			},
			position:{
				width:640,
				height:540
			}
		})

        selector.popUpBox = popUpBox

        selector.totalCount =  Object.keys(config.candidateDataList).length || config.candidateLength || 0
        selector.$dom = $('<div class="addContactTools"></div>')
        selector.$infoBar = $('<div class="infoBar"></div>').appendTo(selector.$dom)
        selector.$infoBarRight = $('<div class="rightPart"></div>').appendTo(selector.$infoBar)



        selector.$tipsBar = $('<div class="tipsBar"></div>').appendTo(selector.$infoBar);
        if(config.candidateLength !== undefined) {
            selector.$totalWrap = $('<div class="totalWrap"><span class="totalText">'+ config.userTypeName +'总数</span></div>').appendTo(selector.$tipsBar)
            selector.$totalCount = $('<span class="totalCount">'+ selector.totalCount +'</span>').appendTo(selector.$totalWrap)
        }

		selector.$dom.on('click','.contact.disabled',function(){
			_Tips($(this).attr('title'));
		})


        selector.searchBar= new SearchBar()
        selector.searchBar.$dom.appendTo(selector.$infoBar)


        //将已选择内容展现在title区域
        selector.$selectWrap = $('<div class="selectWrap"></div>').appendTo(selector.popUpBox.$title.html(''))
        selector.$titleText = $('<span>请选择</span>').prependTo(selector.$selectWrap)
        selector.$selectCount = $('<span class="selectCount">0</span>').appendTo(selector.$selectWrap)
        if(config.checkedMax != undefined) {
    			selector.$checkedInfo=$('<div class="checkedInfo">'+config.checkedMax+'</div>').appendTo(selector.$selectWrap)
    		} else {
          selector.$checkedInfo=$('<div class="checkedInfo">'+ 'all' +'</div>').appendTo(selector.$selectWrap)
        }

        selector.$checkedContact = $('<div class="checkedContactList"></div>').appendTo(selector.$dom)
        selector.checkedList = new CheckedList(config.checkedDataList)
        selector.checkedList.$dom.appendTo(selector.$checkedContact)

        selector.$candidateContact = $('<div class="candidateContactList"></div>').appendTo(selector.$dom)
        selector.$addcontactWrap = $('<div class="addcontactWrap"></div>').appendTo(selector.$candidateContact)
        selector.$emptyContent = $('<div class="emptyContent">暂无结果</div>').appendTo(selector.$candidateContact)
        if(config.hasAddContact) {
            selector.$addContactBtn = $('<div class="btn btn-default">添加'+ config.userTypeName +'</div>').appendTo(selector.$infoBarRight)
        }
        selector.$bottomLeft = $('<div class="bottomLeft"></div>').appendTo(selector.$dom)
        selector.candidateList = new CandidateList(config.candidateDataList)
        selector.candidateList.$dom.appendTo(selector.$candidateContact)

        selector.getCheckedIdList = function () {
            return Object.keys(this.checkedList.newList)
        }
        selector.getCheckedDataList = function () {
            return this.checkedList.getCheckedDataList()
        }

        popUpBox.contentUpdate(selector.$dom)

	}
    window.ContactSelector = ContactSelector
	return ContactSelector;
})
